import { createRouter, createWebHistory } from 'vue-router';
import Main from '../views/Main.vue';
import Login from '../views/Login.vue';
import Search from '../views/SearchPage.vue';
import ManagementPage from '../views/ManagementPage.vue';
import AdminLogin from '../views/AdminLogin.vue';
import Test from '../views/Test.vue';
import SearchResultPage from '../views/SearchResultPage.vue'
import NewQuestionnaire from '../components/NewQuestionnaire/index.vue'

const routes = [{
        path: '/',
        name: 'Login',
        component: Login,
    }, {
        path: '/newQuestionnaire/:id',
        name: 'NewQuestionnaire',
        component: NewQuestionnaire,
    }, {
        path: '/search/:id',
        name: 'SearchResultPage',
        component: SearchResultPage,
    },
    {
        path: '/main/:userid',
        name: 'Main',
        component: Main,
        meta: { requiresAuth: true } // 需要用户身份验证
    },
    {
        path: '/search',
        name: 'Search',
        component: Search,
    },
    {
        path: '/managementPage',
        name: 'ManagementPage',
        component: ManagementPage,
        meta: { requiresManagementAuth: true } // 需要管理身份验证
    },
    {
        path: '/adminLogin',
        name: 'AdminLogin',
        component: AdminLogin,
    },
    {
        path: '/test',
        name: 'Test',
        component: Test,
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 合并导航守卫
router.beforeEach((to, from, next) => {
    const isAuthenticated = !!sessionStorage.getItem('isAuthenticated'); // 检查用户是否已登录
    const isManagementAuthenticated = !!sessionStorage.getItem('isManagementAuthenticated'); // 检查管理员是否已登录

    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!isAuthenticated) {
            next({ name: 'Login' }); // 未登录用户，跳转到登录页面
            return;
        }
    }

    if (to.matched.some(record => record.meta.requiresManagementAuth)) {
        if (!isManagementAuthenticated) {
            next({ name: 'AdminLogin' }); // 未登录管理员，跳转到管理员登录页面
            return;
        }
    }

    next(); // 允许访问
});

export default router;